package com.itheima.aop;

import com.itheima.annotation.JwtOperation;
import com.itheima.annotation.LogOperation;
import com.itheima.mapper.EmpLoginLogMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.LoginInfo;
import com.itheima.util.CurrentHolderJwt;
import com.itheima.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class LoginAspect {
    @Autowired
    private EmpLoginLogMapper empLoginLogMapper;


    @Around("@annotation(log)")
    public Object around(ProceedingJoinPoint pjp, JwtOperation log) throws Throwable {
        // 获取方法执行开始时间
        long begin = System.currentTimeMillis();
        // 执行登录方法
        Object result = pjp.proceed();
        // 获取方法执行结束时间
        long end = System.currentTimeMillis();
        // 获取执行方法的参数
        Object[] args = pjp.getArgs();
        EmpLoginLog empLoginLog = new EmpLoginLog();
        Emp emp= new Emp();
        for (Object arg : args) {
            if (arg instanceof Emp){
                 emp = (Emp) arg;
            }
        }
        empLoginLog.setUsername(emp.getUsername());
        empLoginLog.setPassword(emp.getPassword());
        empLoginLog.setLoginTime(LocalDateTime.now());
        String jwt = null;
        if (result instanceof LoginInfo){
            LoginInfo loginInfo= (LoginInfo) result;
            jwt=loginInfo.getToken();
        }
        empLoginLog.setJwt(jwt);
        short num;
        if (jwt == null){
            num=0;
            empLoginLog.setIsSuccess(num);
        }else {
            num=1;
            empLoginLog.setIsSuccess(num);
        }
        empLoginLog.setCostTime(end-begin);
        empLoginLogMapper.insert(empLoginLog);

        return result;
    }
    public String getUserJwt(){
        return CurrentHolderJwt.getCurrentJwt();
    }
}
